//============================================================================
// Name        : service.cpp
// Author      : Jessica Brazelton
// Course	   : CS 6210 Advanced Operating Systems
// Description :
//============================================================================

//================== HEADER FILES ==================
#include <iostream>						// for I/O
#include <stdio.h>
#include <string>
#include <assert.h>
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/registry.hpp>
#include <xmlrpc-c/server_abyss.hpp>

using namespace xmlrpc_c;
using namespace std;

class flipCoin : public method {
public:
    flipCoin() {
        this -> _signature = "i:ii";
        this->_help = "This method returns heads or tails";
    }

    void execute(paramList const& paramList, value* const retvalP) {
//    	srand(time(NULL));
        *retvalP = value_int(rand() % 2);
    }
};


int main(int size, char* param[]) {
	if (size - 1 != 2) {
		if(strcmp(param[1], "stop") == 0) {
			cout << param[1] << endl;
			return 0;
		} else {
			cout << "You must specify the number of services and/or start/stop" << endl;
			return 1;
		}
	}

	try {
		registry myRegistry;
		methodPtr const flipCoinP(new flipCoin);
		int port = 8080;

		myRegistry.addMethod("flipCoin", flipCoinP);

//		while(true) {
			for(int i = 0; i < atoi(param[1]); i++) {
				serverAbyss myAbyssServer(
							serverAbyss::constrOpt()
							.registryP(&myRegistry)
							.portNumber(port + i)
							.logFileName("/tmp/xmlrpc_log"));

				cout << "Running XML-RPC server on port " << port + i << "..." << endl << endl;
				myAbyssServer.runOnce();
			}
//		}
	} catch (exception const& e) {
		cerr << "Something failed.  " << e.what() << endl;
	}
} // end main
